package com.shengqi.proxy_hook.hook.activityhook;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Build;
import android.util.Log;

import com.shengqi.proxy_hook.R;
import com.shengqi.proxy_hook.hook.Reflector;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

public class SetTextHookHelper {
    private static final String TAG = "MyApplication";

    /**
     * 这里hook了以Context.startActivity方式启动的方法
     */
    public static void doTextHook(Context base) {

        try {
            Reflector reflector = Reflector.with(base);
            Log.e(TAG, "mResources1 = " + reflector.field("mResources").get() + " " + base.getResources().getText(R.string.activity_start_activity));
            reflector.field("mResources").set(new EvilResource(base.getResources()));
            Log.e(TAG, "mResources2 = " + reflector.field("mResources").get() + " " + base.getResources().getText(R.string.activity_start_activity));
//
//            //TODO: 现在我们所有Activity都继承baseactivity，就在所有activity oncreate的时候hook一下resouce也可以；
//
//            //TODO: 看了VirtualApp和Droidplugin的一点代码，但发现每个acitvity的resource都不一样，他们插件化只是想拿到资源，用他们的方法没有用，只能再想办法hook创建resouce的地方；
//            Object loadedApk = reflector.field("mPackageInfo").get();
//            Reflector.with(loadedApk).field("mResources").set(base.getResources());
//            Log.e(TAG, "ResourcesManager = " + reflector.field("mPackageInfo").get());
//
//            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
//            Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
//            Object activityThread = currentActivityThreadMethod.invoke(null);
//
//            Object resManager;
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                Class<?> resourcesManagerClass = Class.forName("android.app.ResourcesManager");
//                Method getInstanceMethod = resourcesManagerClass.getDeclaredMethod("getInstance");
//                resManager = getInstanceMethod.invoke(null);
//                Log.e(TAG, "mResources resManager1 = " + resManager);
////                resManager = android.app.ResourcesManager.getInstance();
//            } else {
//                resManager = Reflector.with(activityThread).field("mResourcesManager").get();
//                Log.e(TAG, "mResources resManager2 = " + resManager);
//            }
//
//            Map<Object, WeakReference<EvilResource>> map = Reflector.with(resManager).field("mActivityResourceReferences").get();
//            Object key = map.keySet().iterator().next();
//            map.put(key, new WeakReference<>(new EvilResource(base.getResources())));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
